#include "stdafx.h"

int OS_STDCALL LicenseCb(unsigned char* pData, size_t ulen, void** lpContext)
{
	rc_assert(ulen != 0, S_ERROR)
	*lpContext = ALLOC_NEW char[ulen + 1]();
	rc_assert(*lpContext != NULL, S_ERROR)
	
	s_memcpy(*lpContext, (char*)pData, ulen);
	return S_SUCCESS;
}
int main_t(_pinstance hInstance, int argc, basic_tchar* argv[])
{
	int	iRes = 0;
	logi("main_t start");

	do {
		HRESULT hr = S_OK;
		basic_tchar szPath[MAX_PATH + 1] = { 0x00 };
		GetExecutePath(INSNULL, szPath, MAX_PATH);
		UINT pathlen = tstring_strlen(szPath);

		CLicenseLoader licnese;
		size_t sLicnese = 0;
		CharArrayPtr pLicenseCode;

		basic_tchar szLicenseName[DYNAMIC_NAME_LEN + 1] = { 0x00 };
		GetDynamicName(_T("license"), szLicenseName, DYNAMIC_NAME_LEN);

		basic_tstring strLicnese(szPath);
		strLicnese.append(path_slash);
		strLicnese.append(szLicenseName);

		hr = licnese.LoadLicnese(strLicnese.c_str());
		rc_assert(hr == S_OK, S_ERROR)

		hr = licnese.func("id", LicenseCb, (void**)&pLicenseCode.m_p, &sLicnese);
		rc_assert(hr == S_OK, S_ERROR)
		//////////////////////////////////////////////////////////////////////////
		CContainer com;

		logi("CreateContainer");
		hr = com.CreateContainer(szPath, pathlen);

		logi("RegisterContainer");
		hr = com.RegisterContainer(pLicenseCode, sLicnese);

		logi("InitContainer");
		hr = com.InitContainer(hInstance, argv, argc);

		logi("RunContainer");
		hr = com.RunContainer(hInstance, argv, argc, 0);

		logi("UnInitContainer");
		hr = com.UnInitContainer(hInstance);

		logi("DestroyContainer");
		iRes = com.GetContainerExitCode();

	} while (iRes == OBJECT_RUN_RET_RESTART);

	logi("main_t end");
	return 0;
}


#if (TARGET_OS == OS_POSIX)
int main(int argc, char* argv[])
{
	_pinstance hInstance = getpid();
	return main_t(hInstance, argc, argv);
}
#elif (TARGET_OS == OS_DARWIN)
int main(int argc, char* argv[])
{
    _pinstance hInstance = getpid();
    return main_t(hInstance, argc, argv);
}
#elif (TARGET_OS == OS_WINDOWS)

int WINAPI WinMain(HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR lpCmdLine,
	int nCmdShow) {

	int iRet = 0;
	int nArgs = 0;
	LPWSTR* szArglist = NULL;
	szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
	iRet = main_t(hInstance, nArgs, szArglist);
	rc_assert(nArgs != 0, 0)
	LocalFree(szArglist);
	return 0;
}
#endif


